//
//  RHMQEndPointDataController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/8/15.
//

#import "RHMQEndPointDataController.h"
#import "RHMQSelPointTypeController.h"
#import "RHMQEndPointModel.h"
#import "RHEndPointDataModel.h"
#import "RHMQTTManage.h"
#import "RHMQDevModel.h"

//五分钟一条
#define time_inteval 600

@interface RHMQEndPointDataController ()<UITableViewDelegate ,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArray;

@property (nonatomic ,strong) QMUILabel *titleLab;

@property (nonatomic ,strong) QMUILabel *codeLab;

@property (nonatomic ,strong) RHMQEndPointModel *curEndPointModel;


@property(nonatomic,strong)NSTimer *timer;

@property (nonatomic, assign) NSInteger currentTimeInteval;

@property (nonatomic, assign) NSInteger count;

@property (nonatomic, strong) QMUIButton *oneDayUploadBtn;
@end

@implementation RHMQEndPointDataController


- (NSArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSArray array];
    }
    return _dataArray;
}

- (void)setCurEndPointModel:(RHMQEndPointModel *)curEndPointModel{
    _curEndPointModel = curEndPointModel;
    [self getDataList];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"数据点上报"];
    [self.view setBackgroundColor:CFTabViewBgColor];
    [self setupUI];
    
}


- (void)setupUI{
    
    QMUIButton *submitBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [submitBtn setFrame:CGRectMake(0, 0,40, 64)];
    [submitBtn setBackgroundColor:UIColor.clearColor];
    [submitBtn setTitleColor:CFMainColor forState:UIControlStateNormal];
    [submitBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [submitBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [submitBtn setTitle:@"上报" forState:UIControlStateNormal];
    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithCustomView:submitBtn];
    self.navigationItem.rightBarButtonItem = rightBarBtn;
    
    UIView *view = [[UIView alloc] init];
    [view setBackgroundColor:UIColor.whiteColor];
    [self.view addSubview:view];
    
    _titleLab = [[QMUILabel alloc] init];
    [_titleLab setTextAlignment:NSTextAlignmentLeft];
    [_titleLab setFont:[UIFont systemFontOfSize:15]];
    [_titleLab setTextColor:kCOLOR_HEX(@"999999")];
    [_titleLab setText:@"请选择端点"];
    [view addSubview:_titleLab];
    
    _codeLab = [[QMUILabel alloc] init];
    [_codeLab setTextAlignment:NSTextAlignmentRight];
    [_codeLab setFont:[UIFont systemFontOfSize:15]];
    [_codeLab setTextColor:kCOLOR_HEX(@"666666")];
    [_codeLab setText:@""];
    [view addSubview:_codeLab];
    
    UIImageView *arrowV = [[UIImageView alloc] init];
    [arrowV setImage:[UIImage imageNamed:@"arrow"]];
    [view addSubview:arrowV];
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [self.view addSubview:_tableView];
    
    
    UITapGestureRecognizer *tapView = [[UITapGestureRecognizer alloc] init];
    view.userInteractionEnabled = YES;
    [view addGestureRecognizer:tapView];
    
    
    kWeakSelf;
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(5);
        make.height.mas_equalTo(50);
    }];
    
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_offset(0);
        make.left.mas_offset(15);
        make.width.mas_equalTo(100);
    }];
    
    [_codeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.titleLab.mas_right);
        make.top.bottom.equalTo(weakSelf.titleLab);
        make.right.equalTo(arrowV.mas_left).offset(-5);
    }];
    
    [arrowV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(20, 20));
        make.right.mas_offset(-15);
        make.centerY.mas_offset(0);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(60, 0, 0, 0));
    }];
    
    [tapView.rac_gestureSignal subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        [weakSelf selectEndPoint];
    }];
    

    [[submitBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf submitDataAction];
    }];
    
    
    QMUIButton *oneDayUploadBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [oneDayUploadBtn setFrame:CGRectMake(0, 0,40, 64)];
    [oneDayUploadBtn setBackgroundColor:CMainColorGreen];
    [oneDayUploadBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [oneDayUploadBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [oneDayUploadBtn setTitle:@"一键上传一天的数据" forState:UIControlStateNormal];
    [self.view addSubview:oneDayUploadBtn];
    [oneDayUploadBtn addTarget:self action:@selector(oneDayDataPreparation) forControlEvents:UIControlEventTouchUpInside];
    self.oneDayUploadBtn = oneDayUploadBtn;
    
    [oneDayUploadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(30);
            make.bottom.right.mas_offset(-30);
            make.height.offset(45);
    }];
    
    QMUIButton *getDataBtn_2 = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [getDataBtn_2 setFrame:CGRectMake(0, 0,40, 64)];
    [getDataBtn_2 setBackgroundColor:CMainColorGreen];
    [getDataBtn_2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [getDataBtn_2.titleLabel setFont:[UIFont systemFontOfSize:18]];
    
    [getDataBtn_2 setTitle:@"获取某一时间段端点数据" forState:UIControlStateNormal];
    [self.view addSubview:getDataBtn_2];
    [getDataBtn_2 addTarget:self action:@selector(getEndPointDataByTime) forControlEvents:UIControlEventTouchUpInside];
    
    [getDataBtn_2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(30);
            make.right.mas_offset(-30);
            make.height.offset(45);
        make.bottom.equalTo(oneDayUploadBtn.mas_top).offset(-30);
    }];
    
    QMUIButton *reportBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [reportBtn setFrame:CGRectMake(0, 0,40, 64)];
    [reportBtn setBackgroundColor:CMainColorGreen];
    [reportBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [reportBtn.titleLabel setFont:[UIFont systemFontOfSize:18]];
    [reportBtn setTitle:@"定时上报" forState:UIControlStateNormal];
    [self.view addSubview:reportBtn];
    [[reportBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (!weakSelf.curEndPointModel) {
            [QMUITips showWithText:@"请选择端点"];
            return;
        }
        reportBtn.userInteractionEnabled = NO;
        [reportBtn setTitle:@"上报中..." forState:UIControlStateNormal];
        [weakSelf timerUploadData];
        weakSelf.timer = [RHCustomTimer scheduledTimerWithTimeInterval:62 target:weakSelf selector:@selector(timerUploadData) userInfo:nil repeats:YES];
    }];
    
    [reportBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.offset(90);
            make.right.mas_offset(-30);
            make.height.offset(45);
        make.bottom.equalTo(getDataBtn_2.mas_top).offset(-30);
    }];
    
    QMUIButton *stopBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [stopBtn setFrame:CGRectMake(0, 0,40, 64)];
    [stopBtn setBackgroundColor:CMainColorGreen];
    [stopBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [stopBtn.titleLabel setFont:[UIFont systemFontOfSize:18]];
    [stopBtn setTitle:@"停止上报" forState:UIControlStateNormal];
    [self.view addSubview:stopBtn];
    [[stopBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf.timer invalidate];
        weakSelf.timer = nil;
        reportBtn.userInteractionEnabled = YES;
        [reportBtn setTitle:@"定时上报" forState:UIControlStateNormal];
    }];
    
    [stopBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.offset(90);
            make.left.mas_offset(30);
            make.height.offset(45);
        make.bottom.equalTo(getDataBtn_2.mas_top).offset(-30);
    }];
}

#pragma mark ------ 获取最后一条端点数据 ----
-(void)getEndPointData
{
//    [self getEndPointDataByTime];
//    return;
    
    if(!self.curEndPointModel){
        [QMUITips showError:@"请选择端点类型"];
        return;
    }
    NSMutableArray *keys = [NSMutableArray array];
    [QMUITips showLoadingInView:self.view];
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        RHEndPointDataModel *model = obj;
        [keys addObject:model.keyCode];
        [model.endpointDataParamConfigs enumerateObjectsUsingBlock:^(RHEndPointDataModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [keys addObject:obj.keyCode];
        }];
    }];
    
    NSDictionary *para = @{@"deviceId":[RHMQTTManage shareMQTTManage].devModel.devId,
                           @"endpointTypeCode":self.curEndPointModel.type,
                           @"keyCodes":keys,
                           @"endpointSn":self.curEndPointModel.sn
    };
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
         
        
    }];
    
}

#pragma mark ------ 获取 某一时间段 端点数据 ----
-(void)getEndPointDataByTime
{
    if(!self.curEndPointModel){
        [QMUITips showError:@"请选择端点类型"];
        return;
    }
    NSString *startTimeStr = @"2023-09-05 00:00:20";
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *startDate = [formatter dateFromString:startTimeStr];
    NSDate *endDate = [NSDate date];
    NSTimeInterval start = [startDate timeIntervalSince1970];
    NSTimeInterval end = [endDate timeIntervalSince1970];
    
    NSMutableArray *keys = [NSMutableArray array];
    [QMUITips showLoadingInView:self.view];
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        RHEndPointDataModel *model = obj;
        [keys addObject:model.keyCode];
        [model.endpointDataParamConfigs enumerateObjectsUsingBlock:^(RHEndPointDataModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [keys addObject:obj.keyCode];
        }];
    }];
    
    NSDictionary *para = @{@"deviceId":[RHMQTTManage shareMQTTManage].devModel.devId,
                           @"startTimestamp":@(start),
                           @"endTimestamp":@(end),
                           @"endpointTypeCode":self.curEndPointModel.type,
                           @"keyCodes":keys,
                           @"endpointSn":self.curEndPointModel.sn
    };
    [BaseModel startWithCompletionAPIKey:D_getEndpointDataByTime argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
         
        
    }];
    
}


//选择端点--
- (void)selectEndPoint{
    RHMQSelPointTypeController *vc = [[RHMQSelPointTypeController alloc] initWithModel:self.curEndPointModel];
    [self.navigationController pushViewController:vc animated:YES];
    kWeakSelf;
    vc.callBackBlock = ^(RHMQEndPointModel * _Nonnull model,NSString *deviceTypeCode) {
        [weakSelf.titleLab setText:model.type];
        [weakSelf.codeLab setText:model.sn];
        weakSelf.curEndPointModel = model;
    };
}

#pragma mark ----------- 一键上传一天的数据 ----------------
-(void)oneDayDataPreparation
{
    if (!_curEndPointModel) {
        [QMUITips showWithText:@"请选择端点"];
        return;
    }
    //上传某一天的
//    NSString *dateStr = @"2023-11-30 00:00:01";
//    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
//    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
//    NSDate *date = [formatter dateFromString:dateStr];
    //上传当天的
    NSDate *date = [NSDate date];
    NSDate *begin_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:0 minute:0 second:0];
    self.currentTimeInteval = (NSInteger)[begin_date timeIntervalSince1970];
    self.count = 0;
    [self uploadOneDayData];
    self.oneDayUploadBtn.userInteractionEnabled = NO;
}

#pragma mark ----------- 一键上传一天的数据 ----------------
-(void)uploadOneDayData
{
    [self createRandomData];
    //上传某一天的
//    NSString *dateStr = @"2023-11-30 00:00:01";
//    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
//    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
//    NSDate *date = [formatter dateFromString:dateStr];
    //上传当天的
    NSDate *date = [NSDate date];
    NSDate *begin_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:0 minute:0 second:0];
    NSDate *end_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:23 minute:59 second:59];
    
    self.count ++;
    NSInteger totalTimeInteval = (NSInteger)[end_date timeIntervalSinceDate:begin_date];
    [self.oneDayUploadBtn setTitle:[NSString stringWithFormat:@"上传中...(%ld/%ld)",self.count,totalTimeInteval/time_inteval] forState:UIControlStateNormal];
    
    self.currentTimeInteval += time_inteval;
    if(self.currentTimeInteval > [end_date timeIntervalSince1970]){
        self.oneDayUploadBtn.userInteractionEnabled = YES;
        [self.oneDayUploadBtn setTitle:@"一键上传一天的数据" forState:UIControlStateNormal];
        return;
    }
    
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:9];
    NSLog(@"----->时间:%@  序列号:%@",[NSDate dateStringWithTimeInterval:self.currentTimeInteval formatter:@"yyyy-MM-dd HH:mm:ss"],randomStr);
    NSString *timeStr = [NSString stringWithFormat:@"%@-%ld",[RHMQTTManage shareMQTTManage].devModel.devId,self.currentTimeInteval];
    NSDictionary *headContent = @{
        @"packCnt":@(1),
        @"packNum":@(1),
        @"packId":randomStr,
        @"cmdId": timeStr,
        @"deviceId": [RHMQTTManage shareMQTTManage].devModel.devId,
        @"deviceType": _curEndPointModel.type,
        @"messageType": @"2", //1下行  2上行
        @"namespace": @"",//上行不用传
        @"payloadVersion": @(1),
        @"timestamp": @(self.currentTimeInteval*1000)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableDictionary *PointDatadic = [NSMutableDictionary dictionary];
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        RHEndPointDataModel *model = obj;
        if(model.content.length>0){
            [PointDatadic setObject:model.content?model.content:@"" forKey:model.keyCode];
        }
        
        [model.endpointDataParamConfigs enumerateObjectsUsingBlock:^(RHEndPointDataModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if(obj.content.length > 0){
                [PointDatadic setObject:ValidNullData(obj.content) forKey:obj.keyCode];
            }
            
        }];
    }];
    
    //时间放data里面
   
    [PointDatadic setObject:@(self.currentTimeInteval*1000) forKey:@"ts"];
    NSDictionary *pointData = @{
        @"data": [PointDatadic yy_modelToJSONString],
        @"deviceId": [RHMQTTManage shareMQTTManage].devModel.devId,
        @"endpointCode": _curEndPointModel.type,
        @"sn": _curEndPointModel.sn
    };
    [bodyDic setObject:pointData forKey:@"pointData"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    NSLog(@"---->%@",[requestPara yy_modelToJSONString]);
    kWeakSelf;
    NSString *pointTopic = [NSString stringWithFormat:@"SERVER/POINT/%@",[RHMQTTManage shareMQTTManage].devModel.devId];
    [[RHMQTTManage shareMQTTManage] sendMessage:[requestPara yy_modelToJSONString] topicSN:pointTopic  handler:^(BOOL isSuccess) {
        if(isSuccess){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf uploadOneDayData];
            });
        }
    }];
    
}




#pragma mark ----- 定时上报 -----
-(void)timerUploadData{
    [self createRandomData];
    [self submitDataAction];
}

//生成随机数据
-(void)createRandomData{

    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        RHEndPointDataModel *model = obj;
        //模拟数据
        if([model.dataType isEqualToString:@"int"]){
            model.content = [NSString stringWithFormat:@"%d",arc4random_uniform(20)+20];
            if(model.isEnum){
                NSArray *enumArr = [model.enums componentsSeparatedByString:@","];
                model.content = [NSString stringWithFormat:@"%ld",arc4random_uniform(enumArr.count)];
            }
        }else if([model.dataType isEqualToString:@"float"]||[model.dataType isEqualToString:@"double"]){
            model.content = [NSString stringWithFormat:@"%d.%d",arc4random_uniform(20)+20,arc4random_uniform(20)+20];
        }
        [model.endpointDataParamConfigs enumerateObjectsUsingBlock:^(RHEndPointDataModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            //模拟数据
            if([obj.dataType isEqualToString:@"int"]){
                obj.content = [NSString stringWithFormat:@"%d",arc4random_uniform(20)+20];
            }else if([model.dataType isEqualToString:@"float"]||[obj.dataType isEqualToString:@"double"]){
                obj.content = [NSString stringWithFormat:@"%d.%d",arc4random_uniform(20)+20,arc4random_uniform(20)+20];
            }else if([model.dataType isEqualToString:@"string"]){
                obj.content =@"1";
            }
        }];
    }];
    [self.tableView reloadData];
   
}

#pragma mark ------ 上报端点数据

- (void)submitDataAction{
    
    if (!_curEndPointModel) {
        [QMUITips showWithText:@"请选择端点"];
        return;
    }
    
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:9];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSString *timeStr = [NSString stringWithFormat:@"%@-%ld",[RHMQTTManage shareMQTTManage].devModel.devId,(NSInteger)interval];
    NSDictionary *headContent = @{
        @"packCnt":@(1),
        @"packNum":@(1),
        @"packId":randomStr,
        @"cmdId": timeStr,
        @"deviceId": [RHMQTTManage shareMQTTManage].devModel.devId,
        @"deviceType": _curEndPointModel.type,
        @"messageType": @"2", //1下行  2上行
        @"namespace": @"",//上行不用传
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableDictionary *PointDatadic = [NSMutableDictionary dictionary];
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        RHEndPointDataModel *model = obj;
        if(model.content.length>0){
            [PointDatadic setObject:model.content?model.content:@"" forKey:model.keyCode];
        }
      
        
        [model.endpointDataParamConfigs enumerateObjectsUsingBlock:^(RHEndPointDataModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if(obj.content.length>0){
                [PointDatadic setObject:ValidNullData(obj.content) forKey:obj.keyCode];
            }
            
        }];
    }];
    [PointDatadic removeObjectForKey:@""];
    //时间放data里面
    NSUInteger time = (NSUInteger)([[NSDate date]timeIntervalSince1970]*1000);
    [PointDatadic setObject:@(time) forKey:@"ts"];
    NSDictionary *pointData = @{
        @"data": [PointDatadic yy_modelToJSONString],
        @"deviceId": [RHMQTTManage shareMQTTManage].devModel.devId,
        @"endpointCode": _curEndPointModel.type,
        @"sn": _curEndPointModel.sn
    };
    [bodyDic setObject:pointData forKey:@"pointData"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    NSLog(@"---->%@",[requestPara yy_modelToJSONString]);
    NSString *pointTopic = [NSString stringWithFormat:@"SERVER/POINT/%@",[RHMQTTManage shareMQTTManage].devModel.devId];
    [[RHMQTTManage shareMQTTManage] sendMessage:[requestPara yy_modelToJSONString] topicSN:pointTopic  handler:^(BOOL isSuccess) {
           
    }];
}

#pragma mark - Network
//获取数据点参数
- (void)getDataList{
    if(!_curEndPointModel){
        return;
    }
    
    [RHEndPointDataModel startWithCompletionAPIKey:D_devDataConfig argument:@{@"endpointTypeCode":_curEndPointModel.type} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.data){
            self.dataArray = resultModel.data;
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}


#pragma mark - UITableViewDelegate ,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    RHEndPointDataModel *model = self.dataArray[section];
    return model.endpointDataParamConfigs.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 55;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UITableViewHeaderFooterView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[NSString stringWithFormat:@"header_%ld",section]];
    
    RHEndPointDataModel *model = self.dataArray[section];
    
    if(headView == nil){
        headView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:[NSString stringWithFormat:@"header_%ld",section]];
        [headView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
        
        [headView.contentView setBackgroundColor:UIColor.whiteColor];
        [headView setBackgroundColor:[UIColor whiteColor]];
        
        UIView *markV = [[UIView alloc] init];
        [markV setBackgroundColor:CFMainColor];
        [headView addSubview:markV];
        
        QMUILabel *titleLab = [[QMUILabel alloc] init];
        [titleLab setTextAlignment:NSTextAlignmentLeft];
        [titleLab setFont:[UIFont systemFontOfSize:14]];
        [titleLab setNumberOfLines:2];
        [titleLab setTextColor:kCOLOR_HEX(@"666666")];
        [headView addSubview:titleLab];
        
        UIView *bgV = [[UIView alloc] init];
        [bgV setBackgroundColor:UIColor.clearColor];
        [bgV.layer setCornerRadius:5];
        [bgV.layer setBorderWidth:1];
        [bgV.layer setBorderColor:kCOLOR_HEX(@"eeeeee").CGColor];
        [headView addSubview:bgV];
        
        QMUITextField *textField = [[QMUITextField alloc] init];
        [textField setKeyboardType:UIKeyboardTypeNumberPad];
        [textField setPlaceholder:@"请输入"];
        [bgV addSubview:textField];
        //模拟数据
        if([model.dataType isEqualToString:@"int"]){
            textField.text = [NSString stringWithFormat:@"%d",arc4random_uniform(20)+20];
        }else if([model.dataType isEqualToString:@"float"]||[model.dataType isEqualToString:@"double"]){
            textField.text = [NSString stringWithFormat:@"%d.%d",arc4random_uniform(20)+20,arc4random_uniform(20)+20];
        }
        
        
        [markV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(5, 30));
            make.left.mas_offset(2);
            make.centerY.mas_offset(0);
        }];
        
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.top.bottom.mas_offset(0);
            make.width.mas_equalTo(200);
        }];
        
        [bgV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(40);
            make.centerY.mas_offset(0);
            make.right.mas_offset(-20);
            make.width.mas_equalTo(100);
        }];
        
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsMake(5, 5, 5, 5));
        }];
        kWeakSelf;
        [[RACSignal merge:@[textField.rac_textSignal, RACObserve(textField, text)]] subscribeNext:^(NSString* text){
            RHEndPointDataModel *section_model = weakSelf.dataArray[section];
            section_model.content = text;
        }];
        
        [titleLab setText:[NSString stringWithFormat:@"%@\n%@",model.keyName,model.remark]];
    }
    
    //模拟数据  cell没用重用,这里只为上下滑动时显示数据
    for (UIView *view in headView.subviews) {
        for (UIView *sub_view in view.subviews) {
            if([sub_view isKindOfClass:[QMUITextField class]]){
                QMUITextField *tf = (QMUITextField*)sub_view;
                if([model.dataType isEqualToString:@"int"]){
                    tf.text = model.content;
                }else if([model.dataType isEqualToString:@"float"]||[model.dataType isEqualToString:@"double"]){
                    tf.text = model.content;
                }else if([model.dataType isEqualToString:@"string"]){
                    tf.text = @"1";
                }
            }
        }
        
    }
    
    
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 55;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 20.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RHEndPointDataModel *model = self.dataArray[indexPath.section];
    RHEndPointDataModel *item_model = model.endpointDataParamConfigs[indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"cell_%ld_%ld",indexPath.section,indexPath.row]];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:@"cell_%ld_%ld",indexPath.section,indexPath.row]];
        
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell.textLabel setFont:[UIFont systemFontOfSize:14]];
        [cell.textLabel setTextColor:kCOLOR_HEX(@"666666")];
        
        UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
        [bgV setBackgroundColor:UIColor.clearColor];
        [bgV.layer setCornerRadius:5];
        [bgV.layer setBorderWidth:1];
        [bgV.layer setBorderColor:kCOLOR_HEX(@"eeeeee").CGColor];
        
        QMUITextField *textField = [[QMUITextField alloc] init];
        [textField setKeyboardType:UIKeyboardTypeNumberPad];
        [textField setPlaceholder:@"请输入"];
        [bgV addSubview:textField];
        //模拟数据
        if([item_model.dataType isEqualToString:@"int"]){
            textField.text = [NSString stringWithFormat:@"%d",arc4random_uniform(20)+20];
        }else if([item_model.dataType isEqualToString:@"float"]||[item_model.dataType isEqualToString:@"double"]){
            textField.text = [NSString stringWithFormat:@"%d.%d",arc4random_uniform(20)+20,arc4random_uniform(20)+20];
        }else if([model.dataType isEqualToString:@"string"]){
            textField.text = @"1";
        }
        
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsMake(5, 5, 5, 5));
        }];
        
        [cell setAccessoryView:bgV];
        kWeakSelf;
        [[RACSignal merge:@[textField.rac_textSignal, RACObserve(textField, text)]] subscribeNext:^(NSString* text){
            NSLog(@"text ==== %@",text);
            //选择端点再回来输入数据后滑动有些cell会没有数据,这里
            RHEndPointDataModel *model = weakSelf.dataArray[indexPath.section];
            RHEndPointDataModel *row_model = model.endpointDataParamConfigs[indexPath.row];
            row_model.content = text;
        }];
    }
    
    [cell.textLabel setText:[NSString stringWithFormat:@"%@\n%@",SafeStr(item_model.keyCode),model.remark]];
    
    //模拟数据
    for (UIView *view in cell.accessoryView.subviews) {
        for (UIView *sub_view in view.subviews) {
            if([sub_view isKindOfClass:[QMUITextField class]]){
                QMUITextField *tf = (QMUITextField*)sub_view;
                if([item_model.dataType isEqualToString:@"int"]){
                    tf.text = model.content;
                }else if([item_model.dataType isEqualToString:@"float"]||[item_model.dataType isEqualToString:@"double"]){
                    tf.text = model.content;
                }else if([model.dataType isEqualToString:@"string"]){
                    tf.text = model.content;
                }
            }
        }
        
    }
    
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  
}

-(void)dealloc
{
    
}

@end
